import https from 'https'

// 原始数据源  
const sources =
{
  "npm": {
    "home": "https://www.npmjs.org",
    "registry": "https://registry.npmjs.org/"
  },
  "yarn": {
    "home": "https://yarnpkg.com",
    "registry": "https://registry.yarnpkg.com/"
  },
  "tencent": {
    "home": "https://mirrors.cloud.tencent.com/npm/",
    "registry": "https://mirrors.cloud.tencent.com/npm/"
  },
  "cnpm": {
    "home": "https://cnpmjs.org",
    "registry": "https://r.cnpmjs.org/"
  },
  "taobao": {
    "home": "https://npmmirror.com",
    "registry": "https://registry.npmmirror.com/"
  },
  "npmMirror": {
    "home": "https://skimdb.npmjs.com/",
    "registry": "https://skimdb.npmjs.com/registry/"
  }
}

// 函数用于发送HEAD请求并返回解析Promise  
function checkSourceSpeed(source) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    const req = https.request(source.registry, (res) => {
      const endTime = Date.now();
      const duration = endTime - startTime;
      resolve({ sourceName:source , duration });
    });
    req.on('error', (error) => {
      reject(error);
    });

    req.end();
  });
}

// 为每个源创建Promise  
const promises = Object.keys(sources).map(sourceName => {
  const source = sources[sourceName];
  return checkSourceSpeed(source);
});
// 使用Promise.race找出哪个源最快  
Promise.race(promises)
  .then(fastestSource => {
    console.log(fastestSource)
    console.log(`最快的源是: ${fastestSource}，耗时: ${fastestSource.duration}ms`);
  })
  .catch(error => {
    console.error('检测源速度时发生错误:', error);
  });